﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Models;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using DevExpress.Web.Mvc;
using System;
using DevExpress.Web.ASPxUploadControl;
using System.IO;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 友情连接管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class LinkTypeManagerController : AdminBaseController
    {
        //
        // GET: /Admin/LinkTypeManager/
        /// <summary>
        /// 友情连接管理首页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_LinkTypeManager", Order = 1)]
        [LogPageActionFilter("友情连接管理", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 树
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult LinkTypeManagerTree()
        {
            TreeModelList treeModelList = new TreeModelList();
            BLL.LinkType linkClassBll = new BLL.LinkType();
            List<Model.LinkType> linkClassAllList = linkClassBll.GetModelList(GlobalConstant.ENTITYNO);

            List<Model.LinkType> linkClassList = linkClassAllList.Where(c => c.FLinkTypeCD != null).ToList();

            TreeItemModel treeParentItemModel = new TreeItemModel(null)
            {
                Id = "0",
                Name = "友情连接类别",
                ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

            };

            if (linkClassList.Count > 0)
            {
                foreach (Model.LinkType linkClass in linkClassList)
                {
                    TreeItemModel treeSonItemModel = new TreeItemModel(treeParentItemModel)
                    {
                        Id = linkClass.FLinkTypeCD,
                        Name = linkClass.FLinkTypeName,
                        ImageUrl = Url.Content("~/Content/ControlImages/scripts_code.png")

                    };

                    treeParentItemModel.Id = "%!^" + treeParentItemModel.Id;

                }
            }
            treeModelList.Add(treeParentItemModel);

            return View(treeModelList);
        }




        /// <summary>
        /// 列表页
        /// </summary>
        /// <param name="linkTypeCD">链接编号</param>
        /// <returns>视图</returns>

        public ActionResult LinkTypeManagerList(string linkTypeCD) 
        {

            if (linkTypeCD == null)
            {
                ViewData["btnAdd"] = false;
            }
            else {
                ViewData["btnAdd"] = true;
            }
            
            int pageIndex = 1;
            List<Model.LinkTypeEntry> linkTypeEntryList = GetLinkTypeManagerList(linkTypeCD, pageIndex);
            ViewData["linkTypeCD"] = linkTypeCD;
            return View(linkTypeEntryList);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示大小</param>
        /// <param name="pageRowSize">每页显示页数</param>
        /// <returns>数据集合</returns>
        private List<Model.LinkTypeEntry> GetLinkTypeManagerList(string linkTypeCD, int pageIndex, int pageRowSize = 0)
        {
            if (null != linkTypeCD)
            {
                linkTypeCD = Fetch.estimateString(linkTypeCD, CheckGetEnum.Safety);
            }
            else
            {
                linkTypeCD = string.Empty;
            }


            BLL.LinkTypeEntry linkTypeEntryBll = new BLL.LinkTypeEntry();


            string where = "FEntityNo='" + GlobalConstant.ENTITYNO + "'";

            if (linkTypeCD != "") {
                where += "and FLinkTypeCD='" + linkTypeCD + "'";
            }


            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("t_LinkTypeEntry", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, where, "FDispSeq", 0, out total);

            List<Model.LinkTypeEntry> linkTypeEntryAllList = new List<Model.LinkTypeEntry>();
            List<Model.LinkTypeEntry> linkTypeEntryList = linkTypeEntryBll.DataTableToListLinkTypeEntry(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                linkTypeEntryAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (linkTypeEntryList.Count > i)
                {
                    linkTypeEntryAllList[((pageIndex - 1) * pageRowSize) + i] = linkTypeEntryList[i];
                }
            }

            return linkTypeEntryAllList;
        }





        /// <summary>
        /// 主要用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult LinkTypeManagerListPartial() 
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string linkTypeCD = Request.Params["linkTypeCD"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }


            List<Model.LinkTypeEntry> linkTypeManagerList = GetLinkTypeManagerList(linkTypeCD, pageIndex, pageRowSize);


            return PartialView("linkTypeManagerListPartial", linkTypeManagerList);
        
        }

        /// <summary>
        /// 批量删除人员数据
        /// </summary>
        /// <param name="linkTypeNos">人员编号</param>
        /// <returns>返回批量删除是否成功</returns>
        [HttpPost]
        public string DeleteManyLinkType(string linkTypeNos)
        {
            string str = string.Empty;
            string[] linkTypeArray = linkTypeNos.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);
            BLL.LinkTypeEntry linkTypeEntryBll = new BLL.LinkTypeEntry();

            try
            {
                linkTypeEntryBll.DelMany(linkTypeArray, GlobalConstant.ENTITYNO);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }

            return str;
        }


        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="linkTypeNo">人员编号</param>
        /// <returns>返回删除是否成功</returns>
        [HttpPost]
        public string DelLinkType(int linkTypeNo)
        {
            string str = string.Empty;
            BLL.LinkTypeEntry linkTypeEntryBll = new BLL.LinkTypeEntry();
            try
            {
                linkTypeEntryBll.DelLinkType(linkTypeNo);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }


        /// <summary>
        /// 实体对象
        /// </summary>
        /// <param name="linkTypeNo">人员编号</param>
        /// <param name="cd">类别编号</param>
        /// <returns>视图</returns>
        public ActionResult LinkTypeContent(string linkTypeNo, string cd) 
        {
            ViewData["img"] = true;
            String linkProp = CheckLinkProp(cd);
            if ("T".Equals(linkProp)) {
                ViewData["img"] = false;
            }
            Model.LinkTypeEntry linkTypeEntry = new Model.LinkTypeEntry();
            if (string.IsNullOrEmpty(linkTypeNo))//增加
            {
                linkTypeEntry.FLinkTypeCD = Fetch.Post("FLinkTypeCD");
                linkTypeEntry.FLinkTypeCD = cd;
            }
            else//修改
            {
                linkTypeNo = Fetch.estimateString(linkTypeNo, CheckGetEnum.Safety);
                BLL.LinkTypeEntry linkTypeEntryBll = new BLL.LinkTypeEntry();
                linkTypeEntry = linkTypeEntryBll.GetModel(Int32.Parse(linkTypeNo));
                ViewData["linkTypeNo"] = linkTypeNo;
            }

            return View(linkTypeEntry);
        }


        /// <summary>
        /// 判断是文本类型的友情连接还是图片（flash）类型的友情连接
        /// </summary>
        /// <param name="linkTypeCD">类别编号</param>
        /// <returns>返回字符串</returns>
        private String CheckLinkProp(String linkTypeCD)
        {
            BLL.LinkType linkTypeBll = new BLL.LinkType();
            Model.LinkType linkType = linkTypeBll.GetModel(linkTypeCD, GlobalConstant.ENTITYNO);
            return linkType.FLinkProp;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="linkTypeEntry">model对象</param>
        /// <param name="linkTypeNo">人员编号</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.LinkTypeEntry linkTypeEntry, string linkTypeNo) 
        {
            ViewData["img"] = true;
            string oldSrvName = "";
            UploadedFile[] fileList = UploadControlExtension.GetUploadedFiles("picUpload");
            if (null != fileList && fileList.Length > 0)
            {
                UploadedFile upload = fileList[0];
                if (upload.ContentLength > 0)
                {
                    string fileSavePath = System.Configuration.ConfigurationManager.AppSettings["FileSavePath"];
                    oldSrvName = linkTypeEntry.FLinkURL;
                    string strImageFileName = FileUpload.UploadFile(upload, fileSavePath + GlobalConstant.ENTITYNO + "/image", ".jpg.gif");
                    linkTypeEntry.FEntityNo = GlobalConstant.ENTITYNO;
                    linkTypeEntry.FFileContent = upload.FileBytes;
                    linkTypeEntry.FNewFileName = fileSavePath + GlobalConstant.ENTITYNO + "/image/" + strImageFileName;
                    linkTypeEntry.FExtName = upload.ContentType;
                    linkTypeEntry.FOldFileName = Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                }
            }
            else {
                linkTypeEntry.FEntityNo = GlobalConstant.ENTITYNO;
            }

            string type = "add";
            string saveType = Fetch.Post("hidSaveType");
            string hidLinkTypeCD = Fetch.Post("hidLinkTypeCD");
            string hidLinkText = Fetch.Post("hidLinkText");
            ViewData["linkTypeNo"] = Fetch.Post("hidlinkTypeNo");
            if (hidLinkTypeCD != string.Empty && hidLinkText !=string.Empty )
            {
                type = "edit";
            }

            ActionResult asctionResult = null;
            BLL.LinkTypeEntry linkTypeEntryBll = new BLL.LinkTypeEntry();           
            try
            {
                if (type == "add")//增加
                {
                    linkTypeEntry.FLinkTypeCD = Fetch.Post("FLinkTypeCD");
                    linkTypeEntryBll.Add(linkTypeEntry);

                }
                else if (type == "edit")//修改
                {
                    linkTypeEntry.FLinkTypeCD = Fetch.Post("FLinkTypeCD");
                    linkTypeEntry.FLinkTypeEntryID = Int32.Parse(Fetch.Post("hidlinkTypeNo"));
                    linkTypeEntryBll.Update(linkTypeEntry);

                }

                ViewData["message"] = "操作成功";
                ViewData["IsClose"] = "Y";
                return View("LinkTypeContent", linkTypeEntry);

            }
            catch (Exception)
            {

                ViewData["message"] = "保存失败";
                ViewData["IsClose"] = "N";
                asctionResult = View("LinkTypeContent", linkTypeEntry);

            }
            return asctionResult;
        }


    }
}
